﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AvantGameMachine.Events
{
    public class EventManager
    {
        private List<Event> localEventList = new List<Event>();
        private Dictionary<long, List<ILocalEventReceiver>> receivers = new Dictionary<long, List<ILocalEventReceiver>>();
        private Dictionary<long, List<ILocalEventReceiver>> clientReceivers = new Dictionary<long, List<ILocalEventReceiver>>();

        public EventManager()
        {
        }

        public void RegisterLocalReceiver(ILocalEventReceiver _receiver,long _eventMask)
        {
            RegisterReceiver(_receiver, _eventMask, receivers);
        }

        private void RegisterReceiver(ILocalEventReceiver _receiver, long _eventMask, Dictionary<long, List<ILocalEventReceiver>> _dictionary)
        {
            int j = sizeof(Int64)*8;
            for (int i = 0; i < j; i++)
            {
                long mask = (long)Math.Pow(2.0, i);
                if ((mask & _eventMask) != 0)
                {
                    List<ILocalEventReceiver> lout;
                    bool result = _dictionary.TryGetValue(mask, out lout);
                    if (!result)
                    {
                        lout = new List<ILocalEventReceiver>();
                    }
                    lout.Add(_receiver);
                    _dictionary[mask] = lout;
                }
            }
        }

        private bool UnregisterReceiver(ILocalEventReceiver _receiver, long _eventMask, Dictionary<long, List<ILocalEventReceiver>> _dictionary)
        {
            bool Deleted = false;

            for (int i = 0; i < sizeof(Int64)*8; i++)
            {
                long mask = (long)Math.Pow(2.0, i);
                if ((mask & _eventMask) != 0)
                {
                    List<ILocalEventReceiver> lout;
                    bool result = _dictionary.TryGetValue(mask, out lout);
                    if (result)
                    {
                        bool tmp = lout.Remove(_receiver);
                        if (!Deleted)
                            Deleted = tmp;
                    }
                }
            }
            return Deleted;
        }

        internal void SendLocalInternalEvent(Event _event)
        {
            SendLocalEvent(_event, receivers);
        }

        internal void SendLocalEvent(Event _event, Dictionary<long, List<ILocalEventReceiver>> _dictionary)
        {
            List<ILocalEventReceiver> lout;
            bool result = _dictionary.TryGetValue(_event.Type, out lout);
            if (result)
            {
                foreach (ILocalEventReceiver ler in lout)
                {
                    ler.ReceiveLocalEvent(_event);
                }
            }
        }
    }
}
